package com.dkha.common.util;

import com.dkha.common.modules.vo.position.PositionVO;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

@Component
public class Base64ImageUtils {

    public static final Logger logger = LoggerFactory.getLogger(Base64ImageUtils.class);

    /**
     * 将网络图片进行Base64位编码
     *
     * @param imageUrl 图片的url路径，如http://.....xx.jpg
     * @return
     */
    public static String encodeImgageToBase64(URL imageUrl) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageUrl);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            byte[] by = outputStream.toByteArray();
            return encoder.encode(by);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


        return null;///encoder.encode(by);// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将网络图片进行Base64位编码
     *
     * @param imageUrl 图片的url路径，如http://.....xx.jpg
     * @return
     */
    public static BufferedImage urlToBufferImage(URL imageUrl) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        try {
            BufferedImage bufferedImage = ImageIO.read(imageUrl);
            return bufferedImage;
        } catch (MalformedURLException e1) {
        } catch (IOException e) {
        } finally {

        }


        return null;///encoder.encode(by);// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将图片流转换为Base64
     *
     * @param bufferedImage
     * @return
     */
    public static String encodeImgageToBase64(BufferedImage bufferedImage) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        ByteArrayOutputStream outputStream = null;
        try {
//            BufferedImage bufferedImage = ImageIO.read(imageUrl);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            byte[] by = outputStream.toByteArray();
            return encoder.encode(by);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


        return null;///encoder.encode(by);// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将本地图片进行Base64位编码
     *
     * @param imageFile 图片的url路径，如F:/.....xx.jpg
     * @return
     */
    public static String encodeImgageToBase64(File imageFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        ByteArrayOutputStream outputStream = null;
        try {
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", outputStream);
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();

            byte[] by = outputStream.toByteArray();
            return encoder.encode(by);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
        // 返回Base64编码过的字节数组字符串
    }

    /**
     * 将Base64位编码的图片进行解码，并保存到指定目录
     *
     * @param base64 base64编码的图片信息
     * @return
     */
    public static void decodeBase64ToImage(String base64, String path,
                                           String imgName) {
        BASE64Decoder decoder = new BASE64Decoder();
        FileOutputStream write = null;
        try {
            write = new FileOutputStream(new File(path
                    + imgName));
            byte[] decoderBytes = decoder.decodeBuffer(base64);
            write.write(decoderBytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                write.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    /**
     * 将Base64位编码的图片进行解码，输出byte
     *
     * @param base64 base64编码的图片信息
     * @return
     */
    public static byte[] decodeBase64ToImage(String base64) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] decoderBytes = decoder.decodeBuffer(base64);
            return decoderBytes;
        } catch (IOException e) {
            return null;
        } finally {
        }
    }

    /**
     * @return
     */
    public static InputStream encodeImgage(BufferedImage subimage) {
        ByteArrayOutputStream outputStream = null;
        try {
            /**如果根据坐标找不到人脸的时候*/
            if (UtilValidate.isNotEmpty(subimage)) {
                outputStream = new ByteArrayOutputStream();
                ImageIO.write(subimage, "png", outputStream);
                byte[] by = outputStream.toByteArray();
                /**将byte转为InputStream*/
                InputStream sbs = new ByteArrayInputStream(by);
                return sbs;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static InputStream encodeImgage(BufferedImage subimage, String imagetype) {
        ByteArrayOutputStream outputStream = null;
        try {
            /**如果根据坐标找不到人脸的时候*/
            if (UtilValidate.isNotEmpty(subimage)) {
                outputStream = new ByteArrayOutputStream();
                ImageIO.write(subimage, "png", outputStream);
                byte[] by = outputStream.toByteArray();
                /**将byte转为InputStream*/
                InputStream sbs = new ByteArrayInputStream(by);
                return sbs;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 对返回的人脸坐标进行扩大处理
     * deelPostion
     *
     * @param picwidth  原图长
     * @param picheight 原图宽
     * @return ImgPositionVO
     */
    public static PositionVO deelPostion(PositionVO positionVO, Integer picwidth, Integer picheight) {

        int xold = positionVO.getX();
        int yold = positionVO.getY();
        int widthold = positionVO.getW();
        int heightold = positionVO.getH();

        int x = ((xold - widthold / 2));
        int y = (yold - heightold / 2);
        int width = widthold * 2;
        int height = heightold * 2;
        if (width > picwidth) {
            width = picwidth;
        }
        if (height > picheight) {
            height = picheight;
        }

        if (x + width > picwidth) {
            x = picwidth-width;
        }
        if (x < 0) {x = 0;}
        if (y + height > picheight) {
            y = picheight-height ;
        }
        if (y < 0) {
            y=0;
        }
        return new PositionVO(x, y, width, height);
    }

    /**
     * 根据坐标 获取头部位置
     *
     * @param
     * @param positionVo 坐标类
     * @return
     */
    public static InputStream encodeHeadImage(BufferedImage bufferedImage, PositionVO positionVo) {
        try {
//            BufferedImage bufferedImage = ImageIO.read(url);
            //获取整个背景图片的宽度和高度
//            int picWidth = bufferedImage.getWidth();
//            int picHeight = bufferedImage.getHeight();
//
//            int xOld = positionVo.getX();
//            int yOld = positionVo.getY();
//            int widthOld = positionVo.getW();
//            int heightOld = positionVo.getH();
//
//            int x = ((xOld - widthOld/2));
//            int y = (yOld - heightOld/2);
//            int width = widthOld * 2;
//            int height = heightOld * 2;
//            if(width > picWidth)
//            {
//                width = picWidth;
//            }
//            if(height > picHeight)
//            {
//                height = picHeight;
//            }
//
//            if(x+width > picWidth)
//            {
//                x = x - picWidth;
//            }
//
//            if(x < 0) {
//                x = 0;
//            }
//            if(y + height > picHeight)
//            {
//                y= y - picHeight;
//
//            }
//            if(y < 0) {
//                y = 0;
//            }
            BufferedImage subimage = bufferedImage.getSubimage(positionVo.getX(), positionVo.getY(), positionVo.getW(), positionVo.getH());
            return encodeImgage(subimage);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * base64转成InputStream
     *
     * @param base64string
     * @return
     */
    public static InputStream BaseToInputStream(String base64string) {
        try {
            byte[] bytes = decodeBase64ToImage(base64string);
            /**将byte转为InputStream*/
            InputStream sbs = new ByteArrayInputStream(bytes);
            return sbs;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

        }
        return null;

    }

    public static void main(String[] args) {
//        URL url = null;
//        try {
//            url = new URL("http://img1.imgtn.bdimg.com/it/u=2064054871,2037178638&fm=200&gp=0.jpg");
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//        String encoderStr = Base64ImageUtils.encodeImgageToBase64(url);
//        System.out.println(encoderStr);
//
//        Base64ImageUtils.decodeBase64ToImage(encoderStr, "E:/", "football.jpg");
//
//        PositionVO positionVO = new PositionVO();
//        positionVO.setX(1080);
//        positionVO.setY(657);
//        positionVO.setW(34);
//        positionVO.setH(43);
//        positionVO.setBgHeight(607);
//        positionVO.setBgWidth(1080);
////        PositionVO positionVO1 =Base64ImageUtils.deelPostion(positionVO,1080,607);
////        logger.info("结果",positionVO1);
//        String a = "http://10.51.10.203:32080/g10203/M00/09/50/CjMKy14eqj-AKvQFAAlJMLj0vEY312.jpg";
//
//
//        BufferedImage bufferedImage = null;
//        try {
//            url = new URL("http://10.51.10.203:32080/g10203/M00/0B/16/CjMKy14e0hyAekdqAAEJd1FBfaY815.jpg");
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//        int x=694;
//        int y=744;
//        int w=240;
//        int h=324;
//        int bgw=1920;
//        int bgh=1080;
//
//        PositionVO positionVO=new PositionVO();
//        positionVO.setW(w);
//        positionVO.setX(x);
//        positionVO.setY(y);
//        positionVO.setH(h);
//        positionVO.setBgWidth(bgw);
//        positionVO.setBgHeight(bgh);
//
//        Gson gson=new Gson();
//        System.out.println(gson.toJson(positionVO));
//        BufferedImage bufferedImage=urlToBufferImage(url);
//        PositionVO positionVO1=deelPostion(positionVO,positionVO.getBgWidth(),positionVO.getBgHeight());
//        System.out.println(gson.toJson(positionVO1));
//        BufferedImage bufferedImage2=bufferedImage.getSubimage(positionVO1.getX(),positionVO1.getY(),positionVO1.getW(),positionVO1.getH());
//        BufferedImage bufferedImage3=bufferedImage.getSubimage(positionVO.getX(),positionVO.getY(),positionVO.getW(),positionVO.getH());
//
//
//
//        try {
//            File file1 =new File("D:/test/curtvedio/img/"+System.currentTimeMillis()+".png");
//            ImageIO.write(bufferedImage2, "png",file1);
//            File file2 =new File("D:/test/curtvedio/img/"+System.currentTimeMillis()+".png");
//            ImageIO.write(bufferedImage3, "png",file2);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//
////        String encoderStr = Base64ImageUtils.encodeImgageToBase64(url);
////        System.out.println(encoderStr);
//
//
////        Base64ImageUtils.decodeBase64ToImage(encoderStr, "E:/", "football.jpg");
//=======
//            bufferedImage = Base64ImageUtils.urlToBufferImage(new URL(a));
//
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//        PositionVO positionVo = Base64ImageUtils.deelPostion(positionVO, bufferedImage.getWidth(), bufferedImage.getHeight());
//        positionVo.setBgHeight(bufferedImage.getHeight());
//        positionVo.setBgWidth(bufferedImage.getWidth());
//        InputStream in = Base64ImageUtils.encodeHeadImage(bufferedImage, positionVo);
//
//        File file = new File("E:/footba.jpg");//文件名        相对路径（项目名根目录下）
//        try {
//            FileOutputStream fos = new FileOutputStream(file);//true表示追加，如果文件存在 向里面继续添加内容
//            byte[] bytes = new byte[1024];
//            while ((in.read(bytes)) != -1) {
//                fos.write(bytes);
//            }
//            in.close();
//            fos.close();//关闭流
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//>>>>>>> 6f675f6d18b0403c24529d795e1b57ca27a1f970

    }

}
